package com.Zheng;

import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;

public class Dui {
    private  int[] arr;
    private int sz;

    public Dui() {
        arr = new int[4];
    }
    public void initArr(int[] a){
        for (int i = 0; i < a.length; i++) {
            if(arr.length==sz) {
                arr= Arrays.copyOf(arr,sz*2);
            }
            arr[i]=a[i];
            sz++;
        }
    }

    public  void jianDaDui() {
        int i =(sz-2)/2;
        for (; i >=0 ; i--) {
            xiangXiaTiaoZhen(i);
        }
    }

    private void xiangXiaTiaoZhen(int pr)
    {
        int ch = 2*pr+1;
        while (ch<sz) {
            if(ch+1<sz&&arr[ch+1]>arr[ch])
                ch++;
            if(arr[ch]>arr[pr]){
                int tmp = arr[ch];
                arr[ch]=arr[pr];
                arr[pr]=tmp;
            }else
                return;
            pr = ch;
            ch = 2*pr+1;
        }
    }

    public void add(int x) {
        if(arr.length==sz) {
            arr= Arrays.copyOf(arr,sz*2);
        }
        arr[sz]=x;
        sz++;
        xiangShangTiaoZhen(sz-1);
    }

    private void xiangShangTiaoZhen(int ch) {
        int pr = (ch-1)/2;
        while (pr>=0) {
            if(arr[ch]>arr[pr]) {
                int tmp = arr[ch];
                arr[ch]=arr[pr];
                arr[pr]=tmp;
            }else
                return;
            ch = pr;
            pr = (ch-1)/2;
        }
    }

    public void print(){
        for (int i = 0; i < sz; i++) {
            System.out.printf("%d ",arr[i]);
        }
        System.out.println();
    }

    public void del()
    {
        int tmp = arr[0];
        arr[0]=arr[sz-1];
        arr[sz-1]=tmp;
        sz--;
        xiangXiaTiaoZhen(0);
    }

    public int[] getArr() {
        return arr;
    }

    public int getSz() {
        return sz;
    }

    public int[] smallestK(int[] arr, int k) {
        int[] ret = new int[k];
        PriorityQueue<Integer> queue = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2-o1;
            }
        });
        for (int i = 0; i < k; i++) {
            queue.offer(arr[i]);
        }
        for (int i = k; i < arr.length; i++) {
            if(!queue.isEmpty()&&arr[i]> queue.peek()){
                queue.poll();
                queue.offer(arr[i]);
            }
        }
        for (int i = 0; i < k; i++) {
            ret[i] = queue.poll();
        }
        return ret;
    }
}